package com.vendar.email;

import java.util.Date;
import java.util.Properties;

import javax.activation.CommandMap;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.activation.MailcapCommandMap;
import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.PasswordAuthentication;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

/*
 * helper class for send emails.
 * usage: create an instance,enter your username&password for verify.
 * setup smtp server if necessary, also smtp port etc.
 * then, your can send email to a list of guys, also with attachments!
 */
public class EMailHelper extends javax.mail.Authenticator {
	private String mUsername = null;
	private String mPassword = null;
	
	private String mFrom = null;
	private String []mRecipients = null;
	
	private String mSubject = null;
	private String mBody = null;
	private String []mAttachment = null;
	
	private String mSmtpHost = null;
	private String mSmtpPort = null;
	
	private boolean mAuth = true;
	private boolean mDebuggable = false;
	
	public EMailHelper(String username,String password){
		SetupUser(username,password);
		SetupServer("smtp.gmail.com","465");
		
		MailcapCommandMap mcm = (MailcapCommandMap)CommandMap.getDefaultCommandMap();
		mcm.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html"); 
		mcm.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml"); 
		mcm.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain"); 
		mcm.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed"); 
		mcm.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822"); 
		CommandMap.setDefaultCommandMap(mcm);
	}
	
	@Override
	public PasswordAuthentication getPasswordAuthentication(){
		return new PasswordAuthentication(mUsername,mPassword);
	}
	
	private Properties GenerateProperties(){
		Properties props = new Properties();
		props.put("mail.debug", mDebuggable?"true":"false");
		props.put("mail.smtp.host", mSmtpHost);
		props.put("mail.smtp.auth", mAuth?"true":"false");
		props.put("mail.smtp.port", mSmtpPort);
		props.put("mail.smtp.socketFactory.port",mSmtpPort);
		props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		props.put("mail.smtp.socketFactory.fallback", "false");
		return props;
	}
	
	public boolean SetupUser(String username,String password){
		this.mUsername = username;
		this.mPassword = password;
		this.mFrom = username; //right? check it!
		return true;
	}
	
	public boolean SetupServer(String smtpHost,String smtpPort){
		this.mSmtpHost = smtpHost;
		this.mSmtpPort = smtpPort;
		return true;
	}
	
	public boolean Send(String []to,String subject, String body,String []attachment){
		mRecipients = to;
		mSubject = subject;
		mBody = body;
		mAttachment = attachment;
		boolean res = false;
		try {
			res = Send();
		} catch (AddressException e) {
			e.printStackTrace();
			return false;
		} catch (MessagingException e) {
			e.printStackTrace();
			return false;
		}
		return res;
	}
	
	private boolean Send() throws AddressException, MessagingException{
		//validity check
		if( mRecipients == null || mSubject == null || mBody == null ){
			System.err.println("email information uncompleted!");
			return false;
		}
		
		Session session = Session.getInstance(GenerateProperties(),this);
		MimeMessage msg = new MimeMessage(session);
		
		//from
		msg.setFrom(new InternetAddress(mFrom));
		//to
		InternetAddress []addressTo = new InternetAddress[mRecipients.length];
		for(int i=0;i<mRecipients.length;++i){
			addressTo[i] = new InternetAddress(mRecipients[i]);
		}
		msg.setRecipients(MimeMessage.RecipientType.TO,addressTo);
		
		//content//
		msg.setSubject(mSubject);
		msg.setSentDate(new Date());
		//body
		BodyPart msgBody = new MimeBodyPart();
		msgBody.setText(mBody);
		Multipart multipart = new MimeMultipart();
		multipart.addBodyPart(msgBody);
		//attachment
		if( mAttachment != null ){
			for(String filename:mAttachment){
				BodyPart attbody = new MimeBodyPart();
				DataSource source = new FileDataSource(filename);
				attbody.setDataHandler(new DataHandler(source));
				attbody.setFileName(filename);
				multipart.addBodyPart(attbody);
			}
		}
		msg.setContent(multipart);
		Transport.send(msg);
		return true;
	}
}
